import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import wea from './images/wea.png';
import { formateDate } from '../../utils/dateUtils';
import memoryUtils from '../../utils/memoryUtils.js';
import storageUtils from '../../utils/storageUtils';
import './index.less';
import menuList from "../../config/menuConfig";

import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import LinkButton from '../link-button';

const { confirm } = Modal;

class Header extends Component {
    
    state = {
        currentTime: formateDate(Date.now()) //当前时间
    };
    
    // 获取实时时间
    getTimes = () => {
        this.intervalId = setInterval(() => {
            this.setState({
                currentTime: formateDate(Date.now())
            });
        },1000);
    }
    
    // 获取菜单对应标题
    getTitle = () => {
        const path = this.props.location.pathname;
        let title = '';
        menuList.forEach(v => {
            if(v.key === path){
                title = v.title;
            }else if(v.children){
                const c = v.children.find(c => path.indexOf(c.key) === 0);
                if(c){
                    title = c.title;
                }
            }
        });
        return title;
    }

    // 登出
    logout = () => {
        // 显示确认框
        confirm({
            title: '确定退出吗？',
            icon: <ExclamationCircleOutlined />,
            onOk: () => {
                // 登出逻辑
                // 删除内存和本地保存的user数据
                // 先删除本地的
                storageUtils.removeUser();
                memoryUtils.user = {};

                // 重定向到login页面
                this.props.history.replace('/login');
            }
        });
    }

    UNSAFE_componentWillMount(){
        this.getTimes();
    }
    
    /**
     * 当前组件卸载前
     */
    componentWillUnmount(){
        // 清楚定时器
        clearInterval(this.intervalId);
        this.intervalId = null;
    }

    render() { 
        const { currentTime } = this.state;
        const { username } = memoryUtils.user;
        const title = this.getTitle();
        return (
            <div className="header">
                <div className="header-top">
                    <span>欢迎, { username }</span>
                    <LinkButton onClick={this.logout}>退出</LinkButton>
                </div>
                <div className="header-bottom">
                    <div className="header-bottom-left">
                        { title }
                    </div>
                    <div className="header-bottom-right">
                        <span>{ currentTime }</span>
                        <img src={wea} alt="" />
                        <span>晴</span>
                    </div>
                </div>
            </div>
        );
    }
}
 
export default withRouter(Header);